from datetime import datetime
from typing import List, Dict, Any, Optional, Literal

from fastapi import APIRouter, HTTPException, Depends
from loguru import logger
from pydantic import BaseModel, Field

from .common import ApiResponse, StandardResponse, ListResponse
from .dependencies import require_auth, require_admin
from ..config.resource import get_knowledge_service
from ..config.settings import settings
from ..models.user import User

router = APIRouter(prefix="/api/knowledge", tags=["知识库管理"])


class KnowledgeBase(BaseModel):
    """知识库模型"""
    id: str = Field(description="知识库ID", examples=["kb_123"])
    name: str = Field(description="知识库名称", examples=["技术文档库"])
    description: str = Field(description="知识库描述", examples=["存储技术相关文档和资料"])
    created_at: datetime = Field(description="创建时间", examples=["2024-01-01T00:00:00"])
    updated_at: datetime = Field(description="更新时间", examples=["2024-01-01T12:00:00"])
    document_count: int = Field(description="文档数量", examples=[15])
    size: int = Field(description="存储大小（字节）", examples=[1024000])
    status: str = Field(description="知识库状态", examples=["active"], enum=["active", "inactive", "building"])


class KnowledgeDocument(BaseModel):
    """知识库文档模型"""
    id: str = Field(description="文档ID", examples=["doc_123"])
    knowledge_base_id: str = Field(description="所属知识库ID", examples=["kb_123"])
    title: str = Field(description="文档标题", examples=["API接口文档"])
    content: str = Field(description="文档内容", examples=["这是一个API接口的详细说明..."])
    file_path: Optional[str] = Field(default=None, description="源文件路径", examples=["/uploads/api_doc.pdf"])
    created_at: datetime = Field(description="创建时间", examples=["2024-01-01T00:00:00"])
    updated_at: datetime = Field(description="更新时间", examples=["2024-01-01T12:00:00"])


class CreateKnowledgeBaseRequest(BaseModel):
    """创建知识库请求"""
    name: str = Field(
        min_length=1, 
        max_length=100, 
        description="知识库名称",
        examples=["技术文档库"]
    )
    description: str = Field(
        min_length=1, 
        max_length=500, 
        description="知识库描述",
        examples=["用于存储和管理技术相关文档和资料"]
    )
    index_type: Optional[str] = Field(
        default="vector", 
        description="知识库索引类型",
        examples=["vector"],
        enum=["vector", "knowledge_graph", "long_document"]
    )
    settings: Optional[Dict[str, Any]] = Field(
        default=None, 
        description="知识库初始设置",
        examples=[{"chunk_size": 512, "chunk_overlap": 50}]
    )


class UpdateKnowledgeBaseRequest(BaseModel):
    """更新知识库请求"""
    name: Optional[str] = Field(
        default=None, 
        min_length=1, 
        max_length=100, 
        description="知识库名称",
        examples=["更新后的技术文档库"]
    )
    description: Optional[str] = Field(
        default=None, 
        min_length=1, 
        max_length=500, 
        description="知识库描述",
        examples=["更新后的描述信息"]
    )


class AddDocumentsRequest(BaseModel):
    """添加文档请求"""
    file_ids: List[str] = Field(
        min_items=1, 
        max_items=50, 
        description="文件ID列表",
        examples=[["file_123", "file_456"]]
    )


class SearchRequest(BaseModel):
    """搜索请求"""
    query: str = Field(
        min_length=1, 
        max_length=200, 
        description="搜索查询内容",
        examples=["如何使用API接口"]
    )
    limit: int = Field(
        default=10, 
        ge=1, 
        le=50, 
        description="返回结果数量限制",
        examples=[10]
    )


# 使用通用响应模型，删除重复定义
KnowledgeBaseResponse = ApiResponse[KnowledgeBase]
KnowledgeBaseListResponse = ListResponse[KnowledgeBase]
KnowledgeDocumentListResponse = ListResponse[KnowledgeDocument]


class FileUploadRequest(BaseModel):
    """文件上传请求"""
    filename: str
    original_filename: str
    file_path: str
    file_size: int
    file_type: str
    mime_type: Optional[str] = None


FileListResponse = ListResponse[Dict[str, Any]]


class KnowledgeBaseSettings(BaseModel):
    """知识库设置模型"""
    chunk_size: int = Field(default=settings.chunk_size)
    chunk_overlap: int = Field(default=settings.chunk_overlap)
    text_split_strategy: Literal['fixed_chars', 'semantic'] = Field(default="fixed_chars")
    split_chars: List[str] = Field(default=["\n\n", "\n", "。"])
    index_type: Literal["vector", "knowledge_graph", "long_document"] = Field(default="vector")  # 'vector' | 'knowledge_graph' | 'long_document'


KnowledgeBaseSettingsResponse = ApiResponse[KnowledgeBaseSettings]


class UpdateKnowledgeBaseSettingsRequest(BaseModel):
    """更新知识库设置请求"""
    chunk_size: int
    chunk_overlap: int
    text_split_strategy: str
    split_chars: List[str]
    index_type: str


@router.get("/bases", 
    response_model=KnowledgeBaseListResponse,
    summary="获取知识库列表",
    description="""
    ## 获取知识库列表接口
    
    获取当前用户可访问的所有知识库列表。
    
    ### 功能特点
    - 分页获取知识库列表
    - 支持按状态过滤
    - 显示知识库统计信息
    - 包含文档数量和存储大小
    
    ### 查询参数
    - **limit**: 返回数量限制（默认50）
    - **offset**: 分页偏移量（默认0）
    - **status**: 状态过滤（可选：active, inactive, building）
    
    ### 返回信息
    - 知识库基本信息
    - 文档数量统计
    - 存储大小统计
    - 创建和更新时间
    
    ### 状态说明
    - **active**: 活跃状态，可正常使用
    - **inactive**: 非活跃状态，暂停使用
    - **building**: 构建中，正在处理文档
    
    ### 错误码
    - **401**: 未认证或会话已过期
    - **500**: 服务器内部错误
    """,
    responses={
        200: {
            "description": "获取知识库列表成功",
            "content": {
                "application/json": {
                    "example": {
                        "success": True,
                        "data": [
                            {
                                "id": "kb_123",
                                "name": "技术文档库",
                                "description": "存储技术相关文档",
                                "created_at": "2024-01-01T00:00:00",
                                "updated_at": "2024-01-01T12:00:00",
                                "document_count": 15,
                                "size": 1024000,
                                "status": "active"
                            }
                        ],
                        "total": 1
                    }
                }
            }
        }
    }
)
async def get_knowledge_bases(
    limit: int = 50, 
    offset: int = 0, 
    status: str = None, 
    _: User = Depends(require_auth)
):
    """获取所有知识库列表"""
    knowledge_service = get_knowledge_service()
    try:
        kbs, total = await knowledge_service.list_knowledge_bases(limit, offset, status)

        # 转换为响应格式
        kb_list = []
        for kb in kbs:
            # 获取统计信息
            stats = await knowledge_service.get_knowledge_base_statistics(kb.id)
            kb_list.append(KnowledgeBase(
                id=kb.id,
                name=kb.name,
                description=kb.description,
                created_at=kb.created_at,
                updated_at=kb.updated_at,
                document_count=stats['file_count'],
                size=stats['total_size'],
                status=kb.status,
            ))

        return KnowledgeBaseListResponse(
            success=True,
            data=kb_list,
            total=total
        )

    except Exception as e:
        logger.exception(f"获取知识库列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取知识库列表失败: {str(e)}")


@router.get("/bases/{kb_id}", response_model=KnowledgeBaseResponse)
async def get_knowledge_base(kb_id: str, _: User = Depends(require_auth)):
    """根据ID获取知识库详情"""
    knowledge_service = get_knowledge_service()
    try:
        kb = await knowledge_service.get_knowledge_base(kb_id)
        if not kb:
            raise HTTPException(status_code=404, detail="知识库不存在")

        # 获取统计信息
        stats = await knowledge_service.get_knowledge_base_statistics(kb_id)

        knowledge_base = KnowledgeBase(
            id=kb.id,
            name=kb.name,
            description=kb.description,
            created_at=kb.created_at,
            updated_at=kb.updated_at,
            document_count=stats['file_count'],
            size=stats['total_size'],
            status=kb.status
        )

        return KnowledgeBaseResponse(
            success=True,
            message="获取知识库详情成功",
            data=knowledge_base
        )

    except HTTPException:
        raise
    except Exception as e:
        logger.exception(f"获取知识库详情失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取知识库详情失败: {str(e)}")


@router.post("/bases", 
    response_model=KnowledgeBaseResponse,
    summary="创建知识库",
    description="""
    ## 创建知识库接口
    
    创建新的知识库，用于存储和管理文档。
    
    ### 功能特点
    - 支持多种索引类型
    - 可配置初始设置
    - 自动创建向量索引
    - 支持不同的文本分割策略
    
    ### 请求参数
    - **name**: 知识库名称（1-100字符，必须唯一）
    - **description**: 知识库描述（1-500字符）
    - **index_type**: 索引类型（vector/knowledge_graph/long_document）
    - **settings**: 初始配置设置（可选）
    
    ### 索引类型说明
    - **vector**: 向量索引，适合一般文档检索
    - **knowledge_graph**: 知识图谱，适合结构化知识
    - **long_document**: 长文档索引，适合大文档处理
    
    ### 默认设置
    - 文本块大小：512字符
    - 重叠大小：50字符
    - 分割策略：固定字符数
    - 分割字符：段落、句号等
    
    ### 错误码
    - **400**: 请求参数错误
    - **401**: 未认证或会话已过期  
    - **409**: 知识库名称已存在
    - **500**: 服务器内部错误
    """,
    responses={
        200: {
            "description": "创建知识库成功",
            "content": {
                "application/json": {
                    "example": {
                        "success": True,
                        "message": "知识库创建成功",
                        "data": {
                            "id": "kb_123",
                            "name": "技术文档库",
                            "description": "存储技术相关文档",
                            "created_at": "2024-01-01T00:00:00",
                            "updated_at": "2024-01-01T00:00:00",
                            "document_count": 0,
                            "size": 0,
                            "status": "active"
                        }
                    }
                }
            }
        },
        409: {
            "description": "知识库名称已存在",
            "content": {
                "application/json": {
                    "example": {"detail": "知识库名称已存在"}
                }
            }
        }
    }
)
async def create_knowledge_base(request: CreateKnowledgeBaseRequest, _: User = Depends(require_auth)):
    """创建新知识库"""
    knowledge_service = get_knowledge_service()
    try:
        # 准备初始设置
        initial_settings = {
            'chunk_size': settings.chunk_size,
            'chunk_overlap': settings.chunk_overlap,
            'text_split_strategy': 'fixed_chars',
            'split_chars': ['\n\n', '\n', '。', '！', '？', '；'],
            'index_type': request.index_type or 'vector'
        }

        # 如果请求中提供了额外设置，则合并
        if request.settings:
            initial_settings.update(request.settings)

        # 使用服务层创建知识库
        kb = await knowledge_service.create_knowledge_base(
            name=request.name,
            description=request.description,
            initial_settings=initial_settings
        )

        knowledge_base = KnowledgeBase(
            id=kb.id,
            name=kb.name,
            description=kb.description,
            created_at=kb.created_at,
            updated_at=kb.updated_at,
            document_count=0,
            size=0,
            status=kb.status
        )

        logger.info(f"创建知识库成功: {request.name} (ID: {kb.id}), 类型: {request.index_type}")

        return KnowledgeBaseResponse(
            success=True,
            message="知识库创建成功",
            data=knowledge_base
        )
    except Exception as e:
        logger.exception(f"创建知识库失败: {e}")
        raise HTTPException(status_code=500, detail=f"创建知识库失败: {str(e)}")


@router.put("/bases/{kb_id}", response_model=KnowledgeBaseResponse)
async def update_knowledge_base(kb_id: str, request: UpdateKnowledgeBaseRequest):
    """更新知识库"""
    knowledge_service = get_knowledge_service()
    try:
        # 使用服务层更新知识库
        kb = await knowledge_service.update_knowledge_base(
            kb_id=kb_id,
            name=request.name,
            description=request.description
        )

        if not kb:
            raise HTTPException(status_code=404, detail="知识库不存在")

        # 获取统计信息
        stats = await knowledge_service.get_knowledge_base_statistics(kb_id)

        knowledge_base = KnowledgeBase(
            id=kb.id,
            name=kb.name,
            description=kb.description,
            created_at=kb.created_at,
            updated_at=kb.updated_at,
            document_count=stats['file_count'],
            size=stats['total_size'],
            status=kb.status
        )

        logger.info(f"更新知识库成功: {kb.name} (ID: {kb_id})")

        return KnowledgeBaseResponse(
            success=True,
            message="知识库更新成功",
            data=knowledge_base
        )

    except ValueError as e:
        logger.warning(f"更新知识库参数错误: {e}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.exception(f"更新知识库失败: {e}")
        raise HTTPException(status_code=500, detail=f"更新知识库失败: {str(e)}")


@router.delete("/bases/{kb_id}", response_model=StandardResponse)
async def delete_knowledge_base(kb_id: str, _: User = Depends(require_admin)):
    """删除知识库"""
    knowledge_service = get_knowledge_service()
    try:
        # 使用服务层删除知识库
        success = await knowledge_service.delete_knowledge_base(kb_id)
        if not success:
            raise HTTPException(status_code=404, detail="知识库不存在")

        logger.info(f"删除知识库成功: (ID: {kb_id})")

        return StandardResponse(
            success=True,
            message="知识库删除成功"
        )

    except Exception as e:
        logger.exception(f"删除知识库失败: {e}")
        raise HTTPException(status_code=500, detail=f"删除知识库失败: {str(e)}")


@router.get("/bases/{kb_id}/files", response_model=StandardResponse)
async def get_knowledge_base_files(kb_id: str, limit: int = 20, offset: int = 0, status: str = None):
    """获取知识库中的文件列表"""
    knowledge_service = get_knowledge_service()
    try:
        # 检查知识库是否存在
        kb = await knowledge_service.get_knowledge_base(kb_id)
        if not kb:
            raise HTTPException(status_code=404, detail="知识库不存在")

        # 获取知识库文件列表
        kb_files, total = await knowledge_service.get_knowledge_base_files(kb_id, limit, offset, status)

        # 转换为响应格式
        file_list = []
        for kb_file in kb_files:
            file_data = {
                "id": kb_file.id,
                "file_id": kb_file.file_id,
                "filename": kb_file.file.filename,
                "original_filename": kb_file.file.original_filename,
                "file_size": kb_file.file.file_size,
                "file_type": kb_file.file.file_type,
                "mime_type": kb_file.file.mime_type,
                "status": kb_file.status,
                "added_at": kb_file.added_at,
                "file_created_at": kb_file.file.created_at
            }
            file_list.append(file_data)

        return StandardResponse(
            success=True,
            message="获取知识库文件列表成功",
            data={
                "files": file_list,
                "total": total,
                "knowledge_base": {
                    "id": kb.id,
                    "name": kb.name,
                    "status": kb.status
                }
            }
        )

    except Exception as e:
        logger.exception(f"获取知识库文件列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取知识库文件列表失败: {str(e)}")


@router.post("/files", response_model=StandardResponse)
async def create_uploaded_file(request: FileUploadRequest):
    """创建上传文件记录"""
    knowledge_service = get_knowledge_service()
    try:
        # 使用服务层创建文件记录
        file_record = await knowledge_service.create_uploaded_file(
            filename=request.filename,
            original_filename=request.original_filename,
            file_path=request.file_path,
            file_size=request.file_size,
            file_type=request.file_type,
            mime_type=request.mime_type
        )

        file_data = {
            "id": file_record.id,
            "filename": file_record.filename,
            "original_filename": file_record.original_filename,
            "file_path": file_record.file_path,
            "file_size": file_record.file_size,
            "file_type": file_record.file_type,
            "mime_type": file_record.mime_type,
            "created_at": file_record.created_at,
            "is_processed": file_record.is_processed,
            "metadata": file_record.metadata or {}
        }

        logger.info(f"创建文件记录成功: {request.filename} (ID: {file_record.id})")

        return StandardResponse(
            success=True,
            message="文件记录创建成功",
            data=file_data
        )

    except Exception as e:
        logger.exception(f"创建文件记录失败: {e}")
        raise HTTPException(status_code=500, detail=f"创建文件记录失败: {str(e)}")


@router.get("/files", response_model=FileListResponse)
async def get_uploaded_files(limit: int = 50, offset: int = 0, file_type: str = None, is_processed: bool = None):
    """获取上传文件列表"""
    knowledge_service = get_knowledge_service()
    try:
        files, total = await knowledge_service.list_uploaded_files(limit, offset, file_type, is_processed)
        file_list = []
        for file_record in files:
            file_data = {
                "id": file_record.id,
                "filename": file_record.filename,
                "original_filename": file_record.original_filename,
                "file_path": file_record.file_path,
                "file_size": file_record.file_size,
                "file_type": file_record.file_type,
                "mime_type": file_record.mime_type,
                "created_at": file_record.created_at,
                "updated_at": file_record.updated_at,
                "is_processed": file_record.is_processed,
                "metadata": file_record.metadata or {}
            }
            file_list.append(file_data)

        return FileListResponse(
            success=True,
            data=file_list,
            total=total
        )

    except Exception as e:
        logger.exception(f"获取文件列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取文件列表失败: {str(e)}")


@router.get("/bases/{kb_id}/documents", response_model=KnowledgeDocumentListResponse)
async def get_knowledge_base_documents(kb_id: str, limit: int = 20, offset: int = 0):
    """获取知识库中的文档列表"""
    knowledge_service = get_knowledge_service()
    try:
        # 检查知识库是否存在
        kb = await knowledge_service.get_knowledge_base(kb_id)
        if not kb:
            raise HTTPException(status_code=404, detail="知识库不存在")
        # 获取知识库文件列表
        kb_files, total = await knowledge_service.get_knowledge_base_files(kb_id, limit, offset)

        # 转换为文档格式
        documents = []
        for kb_file in kb_files:
            document = KnowledgeDocument(
                id=kb_file.id,
                knowledge_base_id=kb_id,
                title=kb_file.file.original_filename or kb_file.file.filename,
                content=f"文件类型: {kb_file.file.file_type}, 大小: {kb_file.file.file_size} bytes",
                file_path=kb_file.file.file_path,
                created_at=kb_file.added_at,
                updated_at=kb_file.file.updated_at
            )
            documents.append(document)
        logger.info(f"获取知识库 {kb_id} 文档列表成功，共 {len(documents)} 个文档")

        return KnowledgeDocumentListResponse(
            success=True,
            data=documents,
            total=total
        )
    except Exception as e:
        logger.exception(f"获取知识库文档列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取知识库文档列表失败: {str(e)}")


@router.post("/bases/{kb_id}/files", 
    response_model=StandardResponse,
    summary="添加文件到知识库",
    description="""
    ## 添加文件到知识库接口
    
    将已上传的文件添加到指定知识库进行处理和索引。
    
    ### 功能特点
    - 批量添加多个文件
    - 自动文档解析和预处理
    - 智能文本分割和向量化
    - 异步处理，支持大文件
    
    ### 处理流程
    1. 验证文件是否存在
    2. 解析文档内容
    3. 文本预处理和清理
    4. 智能分割成文本块
    5. 生成向量嵌入
    6. 存储到知识库索引
    
    ### 请求参数
    - **kb_id**: 知识库ID（路径参数）
    - **file_ids**: 文件ID列表（1-50个文件）
    
    ### 支持的文件类型
    - PDF文档
    - Word文档（DOC, DOCX）
    - 文本文件（TXT, MD）
    - 数据文件（CSV, JSON）
    
    ### 错误码
    - **400**: 请求参数错误
    - **401**: 未认证或会话已过期
    - **404**: 知识库或文件不存在
    - **500**: 服务器内部错误
    """,
    responses={
        200: {
            "description": "添加文件成功",
            "content": {
                "application/json": {
                    "example": {
                        "success": True,
                        "message": "成功添加2个文件到知识库",
                        "data": {
                            "added_files": 2,
                            "failed_files": 0,
                            "processing_status": "started"
                        }
                    }
                }
            }
        },
        404: {
            "description": "知识库不存在",
            "content": {
                "application/json": {
                    "example": {"detail": "指定的知识库不存在"}
                }
            }
        }
    }
)
async def add_files_to_knowledge_base(kb_id: str, request: AddDocumentsRequest, _: User = Depends(require_auth)):
    """向知识库添加文件"""
    knowledge_service = get_knowledge_service()
    try:
        # 使用服务层添加文件到知识库
        added_files, failed_files = await knowledge_service.add_files_to_knowledge_base(kb_id, request.file_ids)

        result_data = {
            "added_count": len(added_files),
            "failed_count": len(failed_files),
            "added_files": [
                {
                    "id": kb_file.id,
                    "file_id": kb_file.file_id,
                    "status": kb_file.status,
                    "added_at": kb_file.added_at
                } for kb_file in added_files
            ],
            "failed_files": failed_files
        }

        message = f"成功添加 {len(added_files)} 个文件"
        if failed_files:
            message += f"，{len(failed_files)} 个文件添加失败"
        logger.info(f"向知识库添加文件: {kb_id}, 成功: {len(added_files)}, 失败: {len(failed_files)}")

        return StandardResponse(
            success=True,
            message=message,
            data=result_data
        )

    except Exception as e:
        logger.exception(f"向知识库添加文件失败: {e}")
        raise HTTPException(status_code=500, detail=f"向知识库添加文件失败: {str(e)}")


@router.delete("/bases/{kb_id}/documents/{document_id}", response_model=StandardResponse)
async def remove_document_from_knowledge_base(kb_id: str, document_id: str):
    """从知识库移除文档"""
    knowledge_service = get_knowledge_service()
    try:
        # 使用服务层移除文件（document_id 实际上是 knowledge_base_file 的 id）
        removed_count, failed_files = await knowledge_service.remove_files_from_knowledge_base(kb_id, [document_id])

        if removed_count == 0:
            if failed_files and "不在知识库中" in failed_files[0]:
                raise HTTPException(status_code=404, detail="文档不在此知识库中")
            else:
                raise HTTPException(status_code=404, detail="文档不存在")

        logger.info(f"从知识库 {kb_id} 移除文档 {document_id}")

        return StandardResponse(
            success=True,
            message="文档移除成功"
        )

    except Exception as e:
        logger.exception(f"移除文档失败: {e}")
        raise HTTPException(status_code=500, detail=f"移除文档失败: {str(e)}")


@router.delete("/bases/{kb_id}/files/{file_id}", response_model=StandardResponse)
async def remove_file_from_knowledge_base(kb_id: str, file_id: str):
    """从知识库移除文件"""
    knowledge_service = get_knowledge_service()
    try:
        # 使用服务层移除文件
        removed_count, failed_files = await knowledge_service.remove_files_from_knowledge_base(kb_id, [file_id])

        if removed_count == 0:
            if failed_files and "不在知识库中" in failed_files[0]:
                raise HTTPException(status_code=404, detail="文件不在此知识库中")
            else:
                raise HTTPException(status_code=404, detail="文件不存在")

        logger.info(f"从知识库 {kb_id} 移除文件 {file_id}")
        return StandardResponse(
            success=True,
            message="文件移除成功"
        )
    except Exception as e:
        logger.exception(f"移除文件失败: {e}")
        raise HTTPException(status_code=500, detail=f"移除文件失败: {str(e)}")


@router.delete("/files/{file_id}", response_model=StandardResponse)
async def delete_uploaded_file(file_id: str):
    """删除上传的文件记录"""
    knowledge_service = get_knowledge_service()
    try:
        success = await knowledge_service.delete_uploaded_file(file_id)
        if not success:
            raise HTTPException(status_code=404, detail="文件不存在")

        logger.info(f"删除文件记录: {file_id}")

        return StandardResponse(
            success=True,
            message="文件删除成功"
        )
    except Exception as e:
        logger.exception(f"删除文件失败: {e}")
        raise HTTPException(status_code=500, detail=f"删除文件失败: {str(e)}")

@router.get("/bases/{kb_id}/data", response_model=StandardResponse)
async def get_knowledge_base_data(kb_id: str, limit: int = 50, offset: int = 0, search: str = None):
    """获取知识库数据片段"""
    knowledge_service = get_knowledge_service()
    try:
        # 检查知识库是否存在
        kb = await knowledge_service.get_knowledge_base(kb_id)
        if not kb:
            raise HTTPException(status_code=404, detail="知识库不存在")

        # 获取知识库中的数据片段
        chunks, total = await knowledge_service.get_knowledge_base_data_chunks(
            kb_id, limit=limit, offset=offset, search_query=search
        )

        return StandardResponse(
            success=True,
            data={
                "chunks": chunks,
                "total": total,
                "limit": limit,
                "offset": offset
            },
            message=f"获取知识库数据成功，共 {total} 个片段"
        )
    except Exception as e:
        logger.exception(f"获取知识库数据失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取知识库数据失败: {str(e)}")


@router.get("/bases/{kb_id}/search", response_model=StandardResponse)
async def search_knowledge_base_data(kb_id: str, query: str, limit: int = 10):
    """搜索知识库数据"""
    knowledge_service = get_knowledge_service()
    try:
        # 检查知识库是否存在
        kb = await knowledge_service.get_knowledge_base(kb_id)
        if not kb:
            raise HTTPException(status_code=404, detail="知识库不存在")

        if not query.strip():
            raise HTTPException(status_code=400, detail="搜索查询不能为空")

        # 搜索知识库数据
        search_results = await knowledge_service.search_knowledge_base_data(kb_id, query, limit)

        return StandardResponse(
            success=True,
            data={
                "results": search_results,
                "query": query,
                "total": len(search_results)
            },
            message=f"搜索完成，找到 {len(search_results)} 个结果"
        )
    except Exception as e:
        logger.exception(f"搜索知识库数据失败: {e}")
        raise HTTPException(status_code=500, detail=f"搜索知识库数据失败: {str(e)}")


@router.get("/bases/{kb_id}/statistics", response_model=StandardResponse)
async def get_knowledge_base_statistics(kb_id: str):
    """获取知识库统计信息"""
    knowledge_service = get_knowledge_service()
    try:
        # 检查知识库是否存在
        kb = await knowledge_service.get_knowledge_base(kb_id)
        if not kb:
            raise HTTPException(status_code=404, detail="知识库不存在")

        # 获取统计信息
        stats = await knowledge_service.get_knowledge_base_statistics(kb_id)

        return StandardResponse(
            success=True,
            message="获取统计信息成功",
            data={
                "knowledge_base": {
                    "id": kb.id,
                    "name": kb.name,
                    "status": kb.status,
                    "created_at": kb.created_at,
                    "updated_at": kb.updated_at
                },
                "statistics": stats
            }
        )

    except Exception as e:
        logger.exception(f"获取知识库统计信息失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取知识库统计信息失败: {str(e)}")


@router.get("/bases/{kb_id}/settings", response_model=KnowledgeBaseSettingsResponse)
async def get_knowledge_base_settings(kb_id: str):
    """获取知识库设置"""
    knowledge_service = get_knowledge_service()
    try:
        # 检查知识库是否存在
        kb = await knowledge_service.get_knowledge_base(kb_id)
        if not kb:
            raise HTTPException(status_code=404, detail="知识库不存在")
        # 获取设置
        base_settings = await knowledge_service.get_knowledge_base_settings(kb_id)
        if base_settings is None:
            # 如果没有找到特定的知识库设置，返回默认设置
            settings_model = KnowledgeBaseSettings()
        else:
            # 如果base_settings是字典，直接使用；如果是对象，则需要转换
            if isinstance(base_settings, dict):
                settings_model = KnowledgeBaseSettings(**base_settings)
            else:
                # 如果已经是KnowledgeBaseSettings对象，直接使用
                settings_model = base_settings

        return KnowledgeBaseSettingsResponse(
            success=True,
            message="获取知识库设置成功",
            data=settings_model
        )
    except Exception as e:
        logger.exception(f"获取知识库设置失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取知识库设置失败: {str(e)}")


@router.put("/bases/{kb_id}/settings", response_model=KnowledgeBaseSettingsResponse)
async def update_knowledge_base_settings(kb_id: str, request: UpdateKnowledgeBaseSettingsRequest):
    """更新知识库设置"""
    knowledge_service = get_knowledge_service()
    try:
        # 检查知识库是否存在
        kb = await knowledge_service.get_knowledge_base(kb_id)
        if not kb:
            raise HTTPException(status_code=404, detail="知识库不存在")

        # 转换请求为字典
        settings_dict = {
            'chunk_size': request.chunk_size,
            'chunk_overlap': request.chunk_overlap,
            'text_split_strategy': request.text_split_strategy,
            'split_chars': request.split_chars,
            'index_type': request.index_type
        }
        # 更新设置
        updated_settings = await knowledge_service.update_knowledge_base_settings(kb_id, settings_dict)
        if updated_settings is None:
            raise HTTPException(status_code=404, detail="知识库不存在")

        settings_model = KnowledgeBaseSettings(**updated_settings)
        logger.info(f"更新知识库设置成功: {kb_id}")
        return KnowledgeBaseSettingsResponse(
            success=True,
            message="知识库设置更新成功",
            data=settings_model
        )
    except Exception as e:
        logger.exception(f"更新知识库设置失败: {e}")
        raise HTTPException(status_code=500, detail=f"更新知识库设置失败: {str(e)}")
